/*
 * Created on Jun 14, 2005
 *
 */
package com.erclab.internal.xpresso.dataAccess;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.exceptions.OptionsException;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.handlers.*;
import com.erclab.internal.xpresso.reports.Report;
import com.erclab.internal.xpresso.security.User;

/**
 * @author Enrique Rodriguez.
 *
 */
public class MysqlOptionsDAO implements OptionsDAO {

	private final String FORM_OPTIONS_QUERY = "SELECT * FROM options WHERE options.idForm=? ORDER BY DisplayOrder";
	private final String REPORT_OPTIONS_QUERY = "SELECT * FROM options WHERE options.idReport=? ORDER BY DisplayOrder";
	

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.dataAccess.OptionsDAO#loadReportOptions(com.erclab.internal.xpresso.reports.Report, com.erclab.internal.xpresso.security.User)
	 */
	public void loadReportOptions(Report theReport, User theUser)
		throws OptionsException {
		// Load report options
		String idReportString = "" + theReport.getIdReport();
		ResultSetHandler rsHandler = new OptionsHandler(theUser);
		QueryRunner run = new QueryRunner((DataSource)Settings.getRepository().getRepositoryDataSource(theReport.getReportName()));
		try {
			theReport.setOptions((ArrayList)run.query(REPORT_OPTIONS_QUERY, idReportString, rsHandler));
		}catch(SQLException ex){
			throw new OptionsException("There was an error loading the report options:" + ex);
		}
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.dataAccess.OptionsDAO#loadFormOptions(com.erclab.internal.xpresso.forms.Form, com.erclab.internal.xpresso.security.User)
	 */
	public void loadFormOptions(Form theForm, User theUser)
		throws OptionsException {
		// Load form options
		String idFormString = "" + theForm.getIdForm();
		ResultSetHandler rsHandler = new OptionsHandler(theUser);
		QueryRunner run = new QueryRunner((DataSource)Settings.getRepository().getRepositoryDataSource(theForm.getFormName()));
		try {
			theForm.setOptions((ArrayList)run.query(FORM_OPTIONS_QUERY, idFormString, rsHandler));
		}catch(SQLException ex){
			throw new OptionsException("There was an error loading the form options:" + ex);
		}	
	}

}
